// 获取元素对象
const goods_list = document.getElementById('goods_list');
const order_content = document.getElementById('order_content');
const submit_btn = document.getElementById('submit_btn');
const output_btn = document.getElementById('output_btn');
const cancel_btn = document.getElementById('cancel_btn');
const username_tv = document.getElementById('username');
const avater_img = document.getElementById('avater');
const op_goods = document.getElementById('op_goods');
const op_order = document.getElementById('op_order');
const goods_pager = document.getElementById('goods_pager');
const order_pager = document.getElementById('order_pager');
const order_details = document.getElementById('order_details');

// 预设商品列表
var goodsList =
    [{ text: "智能小车1", imgSrc: "./img/goods.png" },
    { text: "智能小车2", imgSrc: "./img/goods.png" },
    { text: "智能小车3", imgSrc: "./img/goods.png" },
    { text: "智能小车4", imgSrc: "./img/goods.png" },
    { text: "智能小车5", imgSrc: "./img/goods.png" },
    { text: "智能小车6", imgSrc: "./img/goods.png" },
    { text: "智能小车7", imgSrc: "./img/goods.png" },
    { text: "智能小车8", imgSrc: "./img/goods.png" },
    { text: "智能小车9", imgSrc: "./img/goods.png" },
    { text: "智能小车10", imgSrc: "./img/goods.png" }];

// 订单内容JsonArray
var orderListJSON = [];

// api
const apiUrl = "https://im.aurora.hk.cn/api/";
var username = "Admin";
var password = "123";
// 登录状态
var isLogined = false;

// 登录
function login() {
    // 已登录时
    if (isLogined) {
        alert("您已登录！");
        return;
    }
    // 准备要发送的数据
    var data = new URLSearchParams();
    data.append("username", username);
    data.append("password", password);

    // 发起POST请求
    fetch(apiUrl + "login.php", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        body: data,
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.text();
        })
        .then(data => {
            data = JSON.parse(data);
            // 请求成功
            console.log(data);
            if (data.status == 200) {
                isLogined = true;
                username_tv.innerText = username;
                alert("登录成功！");
            } else {
                alert("登录失败！");
            }
        })
        .catch(error => {
            // 请求失败
            console.error('error:', error);
        });
}

// 获取订单信息
function getOrderDetails() {
    // 准备要发送的数据
    var data = new URLSearchParams();
    data.append("username", username);
    data.append("password", password);

    // 发起POST请求
    fetch(apiUrl + "get_orders.php", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        body: data,
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.text();
        })
        .then(data => {
            // 请求成功
            data = JSON.parse(data);
            if (data.status == 200) {
                console.log(data);
                order_details.innerHTML = '';
                // 遍历商品列表
                for (var i = 0; i < data.user_orders.length; i++) {
                    const order = data.user_orders[i];
                    const orderNumber = "订单号：" + order['order_number'];
                    var orderContent = "";
                    for (var key in order['order_content']) {
                        orderContent += "产品名：" + order['order_content'][key]['name'] + "\n";
                        orderContent += "数量：" + order['order_content'][key]['counts'] + "\n";
                    }
                    const orderTime = "下单时间：" + order['order_time'];
                    const orderInfo = orderNumber + "\n\n" + orderContent + "\n" + orderTime;
                    // console.log(orderInfo);
                    const item = document.createElement('div');
                    item.classList.add('order_item');
                    item.innerText = orderInfo;
                    order_details.appendChild(item);
                }
            }
        })
        .catch(error => {
            // 请求失败
            console.error('error:', error);
        });
}

// 订单提交
function submitOrder() {
    // 未登录
    if (!isLogined) {
        alert("您还没有登录！");
        return;
    } else if (orderListJSON.length == 0) {
        alert("您还没有添加订单！");
        return;
    }
    // 准备要发送的数据
    var data = new URLSearchParams();
    data.append("username", username);
    data.append("password", password);
    data.append("order_content", JSON.stringify(orderListJSON));

    // 发起POST请求
    fetch(apiUrl + "place_order.php", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        body: data,
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.text();
        })
        .then(data => {
            // 请求成功
            data = JSON.parse(data);
            if (data.status == 200) {
                console.log(data);
                alert("下单成功！");
            }
        })
        .catch(error => {
            // 请求失败
            console.error('error:', error);
        });
}

// 订单更新
function updateOrder(name, counts) {
    if (orderListJSON.length == 0) {
        orderListJSON.push({ "name": name, "counts": counts });
    }
    else {
        var isNewGoods = true;
        for (const item of orderListJSON) {
            if (name == item.name) {
                // 已有产品
                isNewGoods = false;
                item.counts += counts;
                break;
            }
        }
        if (isNewGoods) {
            // 第二产品加入订单 
            orderListJSON.push({ "name": name, "counts": counts });
        }
    }
    // 刷新界面
    var orderContent = "";
    for (var i = 0; i < orderListJSON.length; i++) {
        orderContent += "产品名：" + orderListJSON[i].name + "\n数量：" + orderListJSON[i].counts + "\n";
    }
    // console.log(orderContent);
    order_content.innerText = orderContent;
}

// 订单取消
function cancelOrder() {
    if (orderListJSON.length == 0) {
        alert("您还没有添加订单！");
        return;
    }
    orderListJSON = [];
    // 刷新界面
    order_content.innerText = "空空如也~";
    alert("成功！");
}

// 加入订单
function addOrderList() {
    // 获取父级li元素
    var parentLi = this.parentElement;
    // 获取title
    var name = parentLi.querySelector('.title').textContent;
    // 获取num
    var counts = parseInt(parentLi.querySelector('input').value);
    if (counts > 0) {
        updateOrder(name, counts);
        alert("加入订单成功");
    } else {
        alert("请输入产品数量！");
    }
}

// 创建商品列表
for (var i = 0; i < goodsList.length; i++) {
    // 创建li
    var liElement = document.createElement('li');
    // 创建image
    var imageElement = document.createElement("img");
    imageElement.src = goodsList[i].imgSrc;
    imageElement.classList.add('img');

    // 创建title
    var titleElement = document.createElement('h4');
    titleElement.textContent = goodsList[i].text;
    titleElement.classList.add('title');

    // 创建数量选择框
    var numDiv = document.createElement('div');
    numDiv.style.width = "75%";
    numDiv.style.display = "flex";
    numDiv.style.flexDirection = "row";
    var numText = document.createElement('span');
    numText.textContent = "数量：";
    numText.style.fontSize = "15px";
    var numInput = document.createElement('input');
    numInput.style.width = '60%';
    numInput.style.height = '20px';
    numInput.style.textAlign = 'center';
    numDiv.appendChild(numText);
    numDiv.appendChild(numInput);

    // 创建按钮
    var btn = document.createElement('div');
    btn.textContent = "加入订单";
    btn.classList.add('btn');

    // 添加点击事件监听器
    btn.addEventListener('click', addOrderList);

    // 添加到ul
    liElement.appendChild(imageElement);
    liElement.appendChild(titleElement);
    liElement.appendChild(numDiv);
    liElement.appendChild(btn);
    goods_list.appendChild(liElement);
}

// 导出csv
function exportToCSV() {
    if (!isLogined) {
        alert("您还没有登录！");
        return;
    } else if (orderListJSON.length == 0) {
        alert('您还没有添加订单信息！');
        return;
    }

    var jsonData = orderListJSON;
    // 构建CSV字符串
    var csv = "";
    var keys = Object.keys(jsonData[0]);

    // 添加表头
    csv += keys.join(",") + "\n";

    // 添加数据行
    jsonData.forEach(function (row) {
        csv += keys.map(key => row[key]).join(",") + "\n";
    });

    // 创建blob，将数据字符串编码为UTF-8
    var csvData = new Blob(["\uFEFF" + csv], { type: 'text/csv;charset=UTF-8' });

    // 创建下载链接
    var csvUrl = URL.createObjectURL(csvData);
    var a = document.createElement('a');
    a.href = csvUrl;

    // 文件命名
    const nowDate = new Date();
    const timeString = `${nowDate.getFullYear()}${(nowDate.getMonth() + 1).toString().padStart(2, '0')}${nowDate.getDate().toString().padStart(2, '0')}${nowDate.getHours().toString().padStart(2, '0')}${nowDate.getMinutes().toString().padStart(2, '0')}${nowDate.getSeconds().toString().padStart(2, '0')}`;
    a.download = "ORD_" + timeString + '.csv';

    // 添加链接到文档并触发点击
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

// 选项卡
op_goods.addEventListener('click', function () {
    goods_pager.style.display = 'block';
    order_pager.style.display = 'none';
    op_goods.style.color = '#fff';
    op_goods.style.backgroundColor = 'rgb(22, 135, 235)';
    op_order.style.color = 'rgb(94, 93, 93)';
    op_order.style.backgroundColor = 'rgb(235, 235, 235)';
});

op_order.addEventListener('click', function () {
    if (!isLogined) {
        alert("您还没有登录！");
    } else {
        goods_pager.style.display = 'none';
        order_pager.style.display = 'block';
        op_goods.style.color = 'rgb(94, 93, 93)';
        op_goods.style.backgroundColor = 'rgb(235, 235, 235)';
        op_order.style.color = '#fff';
        op_order.style.backgroundColor = 'rgb(22, 135, 235)';
        getOrderDetails();
    }
});

// 添加事件
avater_img.addEventListener('click', login);
submit_btn.addEventListener('click', submitOrder);
cancel_btn.addEventListener('click', cancelOrder);
output_btn.addEventListener('click', exportToCSV);
